import tkinter as tk
from PIL import Image, ImageDraw, ImageTk
import random

# 线性函数
def line(x, a, b):
    return x * a + b
# 绘制线性函数
def draw_line(canvas, a, b):
    w = 400
    h = 400
    m = 30
    gap = 50
    size = 100
    px = 5
    xy = []

    # 绘制简单的X轴坐标
    for w_x in range(m, w, gap):
        canvas.create_text(w_x, h + m, text=str(w_x - m), anchor="s")

    # 绘制简单的Y轴坐标
    for h_y in range(h, 0, -gap):
        if h - h_y != 0:
            canvas.create_text(m - 2, h_y, text=str(h - h_y), anchor="e")



    # 绘制白色背景图
    new_img = Image.new("RGB", (w, h), "white")
    draw = ImageDraw.Draw(new_img)
    # 绘制线条
    for x in range(w):
        y = line(x, a, b)
        new_y = h - y
        if new_y > 0:
            draw.point((x, new_y), fill="blue")

    # 渲染到坐标图中
    img = ImageTk.PhotoImage(new_img)
    canvas.create_image(m, 1, image=img, anchor="nw")
    canvas.image = img



    # 生成新的坐标点
    for i in range(size):
        x = int(w * random.random())
        y = int(h * random.random())
        xy.append([x, y])
        f_y = line(x, a, b)
        # 绘制圆形红点
        if y > f_y:
            canvas.create_oval(x - px // 2 + m, h - y - px // 2, x + px // 2 + m, h - y + px // 2, fill="red")
        else:
            # 绘制矩形黑点
            canvas.create_rectangle(x + m, h - y, x + px + m, h - y + px, fill="black")


def run():
    a = float(a_entry.get())
    b = float(b_entry.get())
    draw_line(canvas, a, b)

root = tk.Tk()
root.title("线性函数")
root.geometry("500x500")
# 按钮区域
frame = tk.Frame(root)
frame.pack()
tk.Label(frame, text="系数（权重）").pack(side="left")
a_entry = tk.Entry(frame,width=3)
a_entry.insert(0, "0.5")
a_entry.pack(side="left")

tk.Label(frame, text="常量（垂直偏移量）").pack(side="left")
b_entry = tk.Entry(frame,width=3)
b_entry.insert(0, "10")
b_entry.pack(side="left")

tk.Button(frame, text="绘制点", command=run).pack(side="left")

# 创建画布
canvas = tk.Canvas(root, width=431, height=431)
canvas.pack()

root.mainloop()